package com.shanks.framework.mq.rocketmq.listener;


import cn.hutool.extra.spring.SpringUtil;
import com.shanks.framework.mq.rocketmq.config.RocketMQConsumerInitializer;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Component
public class RocketMQConsumerApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger logger = LoggerFactory.getLogger(RocketMQConsumerApplicationListener.class);

    private boolean isExecuted = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (isExecuted) {
            return; // 防止重复执行
        }

        ApplicationContext context = event.getApplicationContext();
        if (!isMainAppContext(context)) {
            return;
        }

        // 获取所有 RocketMQ 消费者初始化器
        Map<String, RocketMQConsumerInitializer> initializerMap = SpringUtil.getBeansOfType(RocketMQConsumerInitializer.class);

        if (initializerMap == null || initializerMap.isEmpty()) {
            logger.warn("没有找到任何 RocketMQConsumerInitializer Bean，跳过消费者启动。");
            return;
        }

        if (initializerMap.size() > 1) {
            logger.error("发现多个 RocketMQConsumerInitializer 实例: {}", initializerMap.keySet());
        }

        List<String> successList = new ArrayList<>();
        List<String> failureList = new ArrayList<>();

        // 启动每个消费者
        for (RocketMQConsumerInitializer initializer : initializerMap.values()) {
            for (Map.Entry<String, DefaultMQPushConsumer> entry : initializer.getConsumersMap().entrySet()) {
                String consumerName = entry.getKey();
                DefaultMQPushConsumer consumer = entry.getValue();

                try {
                    consumer.start();
                    successList.add(consumerName);
                    logger.info("RocketMQ 消费者启动成功: {}", consumerName);
                } catch (Exception e) {
                    failureList.add(consumerName);
                    logger.error("RocketMQ 消费者启动失败: {}", consumerName, e);
                }
            }
        }

        // 总结启动结果
        if (!successList.isEmpty()) {
            logger.info("RocketMQ 消费者启动成功列表: {}", successList);
        }
        if (!failureList.isEmpty()) {
            logger.error("RocketMQ 消费者启动失败列表: {}", failureList);
        }

        isExecuted = true;
    }

    /**
     * 判断是否为主应用的 ApplicationContext。
     * 排除 bootstrap、Ribbon SpringClientFactory（Swagger Client API）的子上下文等。
     *
     * @param context 应用上下文
     * @return 是否为主应用上下文
     */
    private boolean isMainAppContext(ApplicationContext context) {
        String appName = context.getEnvironment().getProperty("spring.application.name");
        return appName != null && !appName.equals("bootstrap") && context.getId().startsWith(appName);
    }
}

